package com.dog.service.impl;

import com.dog.dao.ContactPersonDAO;
import com.dog.model.ContactPerson;
import com.dog.model.Customer;
import com.dog.model.Role;
import com.dog.service.IContactPersonService;
import com.dog.service.ICustomerService;
import com.dog.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * User: Kuttubek Aidaraliev
 * Date: 03.05.2010
 * Time: 8:03:55
 */
@Service
public class ContactPersonService extends BaseService<ContactPersonDAO, ContactPerson>
        implements IContactPersonService {

    @Autowired
    private ContactPersonDAO contactPersonDAO;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private ICustomerService customerService;

    @Override
    public ContactPersonDAO getDao() {
        return contactPersonDAO;
    }

    @Override
    public ContactPerson getByIdWithRoles(Long contactPersonId) {
        return getDao().getByIdWithRoles(contactPersonId);
    }

    @Override
    public void addRole(Long roleId, Long contactPersonId) {
       ContactPerson contactPerson = getByIdWithRoles(contactPersonId);
       Role role = roleService.get(roleId);
       contactPerson.getRoles().add(role);
       getDao().update(contactPerson);
    }

    @Override
    public void deleteRole(Long roleId, Long contactPersonId) {
        ContactPerson contactPerson = getByIdWithRoles(contactPersonId);
        Role role = roleService.get(roleId);
        contactPerson.getRoles().remove(role);
        getDao().update(contactPerson);
    }

    @Override
    public ContactPerson save(ContactPerson contactPerson){
        //This method will reImplements
        contactPersonDAO.save(contactPerson);
        contactPerson = get(contactPerson.getId());
        Customer customer = contactPerson.getCustomer();

        if (customer == null) {
            return contactPerson;
        }

        customerService.addContactPerson(customer.getId(), contactPerson);

        return contactPerson;

    }
}
